import React, { useState, useEffect } from 'react';
import { Card, Table, Tag, DatePicker, Space, Button, message } from 'antd';
import { getAttendanceHistory } from '../../api/attendance';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

/**
 * 管理员考勤管理页面
 * 显示所有员工的考勤记录
 */
const AdminAttendance = () => {
    const [loading, setLoading] = useState(false);
    const [attendanceData, setAttendanceData] = useState([]);
    const [dateRange, setDateRange] = useState([]);

    useEffect(() => {
        // 设置默认日期范围为当前月份
        const today = dayjs();
        const startDate = today.startOf('month');
        const endDate = today.endOf('month');
        setDateRange([startDate, endDate]);
        
        // 初始加载数据
        fetchAttendanceData(startDate, endDate);
    }, []);

    // 考勤状态映射
    const statusMap = {
        1: { text: '未打卡', color: 'default' },
        2: { text: '正常', color: 'success' },
        3: { text: '迟到', color: 'warning' },
        4: { text: '早退', color: 'warning' },
        5: { text: '缺勤', color: 'error' },
    };

    // 表格列定义
    const columns = [
        {
            title: '员工ID',
            dataIndex: 'employee_id',
            key: 'employeeId',
        },
        {
            title: '员工姓名',
            dataIndex: ['employee', 'name'],
            key: 'employeeName',
        },
        {
            title: '部门',
            dataIndex: ['employee', 'department', 'name'],
            key: 'department',
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            sorter: (a, b) => new Date(a.date) - new Date(b.date),
        },
        {
            title: '签到时间',
            dataIndex: 'check_in_time',
            key: 'checkInTime',
        },
        {
            title: '签退时间',
            dataIndex: 'check_out_time',
            key: 'checkOutTime',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={statusMap[status]?.color}>
                    {statusMap[status]?.text}
                </Tag>
            ),
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Button type="link" onClick={() => handleEdit(record)}>
                    修改
                </Button>
            ),
        },
    ];

    // 获取考勤记录
    const fetchAttendanceData = async (start, end) => {
        const startDate = start || dateRange[0];
        const endDate = end || dateRange[1];
        
        if (!startDate || !endDate) {
            message.warning('请选择日期范围');
            return;
        }

        setLoading(true);
        try {
            const response = await getAttendanceHistory({
                startDate: startDate.format('YYYY-MM-DD'),
                endDate: endDate.format('YYYY-MM-DD')
            });

            setAttendanceData(response.data || []);
        } catch (error) {
            console.error('获取考勤记录失败:', error);
            message.error('获取考勤记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 日期范围变化处理
    const handleDateRangeChange = (dates) => {
        setDateRange(dates);
    };

    // 导出考勤记录
    const handleExport = () => {
        // TODO: 实现导出功能
        message.info('导出功能开发中');
    };

    // 编辑考勤记录
    const handleEdit = (record) => {
        message.info(`正在编辑员工 ${record.employee?.name || ''} 的考勤记录`);
        // TODO: 实现编辑逻辑
    };

    return (
        <Card title="考勤记录管理">
            <Space style={{ marginBottom: 16 }}>
                <RangePicker
                    onChange={handleDateRangeChange}
                    value={dateRange}
                />
                <Button type="primary" onClick={() => fetchAttendanceData()}>
                    查询
                </Button>
                <Button onClick={handleExport}>
                    导出
                </Button>
            </Space>

            <Table
                columns={columns}
                dataSource={attendanceData}
                rowKey="id"
                loading={loading}
                pagination={{
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条记录`,
                }}
            />
        </Card>
    );
};

export default AdminAttendance;